package cn.singno.bob.coffice.utils;

import java.lang.reflect.Field;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.PrintSetup;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;

import cn.singno.bob.coffice.bean.ExecleDocument;
import cn.singno.bob.common.utils.CalendarUtil;
import cn.singno.bob.common.utils.ReflectionUtils;

/**
 * <p>名称：ExecleUtils.java</p>
 * <p>描述：execle工具类</p>
 * <pre>
 * 	说明：该方法Bean映射，调用该方法中的getXxx()方法
 * 	   获取方法，以字段的先后来获取，请排序好字段   
 * </pre>
 * @author 鲍建明
 * @date 2014年8月6日 下午12:37:50
 * @version 1.0.0
 */
public class ExecleUtils {


    /**
     * 创建Execle表格
     * @param execleView
     * @return
     */
    public static ExecleDocument createExecle(ExecleDocument execleView){
    	Workbook workBook = new HSSFWorkbook();							//声明一个工作薄
    	
    	Sheet sheet =  workBook.createSheet(execleView.getTableName());		// 生成一个表格
    	
    	Map<String, CellStyle> styles = createStyles(workBook);			//创建样式和字体
    	
		PrintSetup printSetup = sheet.getPrintSetup();
		printSetup.setLandscape(true);
		sheet.setFitToPage(true);
		sheet.setHorizontallyCenter(true);
		sheet.setDefaultColumnWidth(17);
		
		createExecleTitle(sheet, styles, execleView.getTableTitle());
		createExecleHeader(sheet, styles, execleView.getHeaders());
		createExecleBody(sheet, styles, execleView, workBook);
		execleView.setWorkbook(workBook);
		return execleView;
    }
    
    /**
     * 创建标题
     * @param sheet
     * @param styles
     * @param tableTitle
     */
    private static void createExecleTitle(Sheet sheet, Map<String, CellStyle> styles, String tableTitle){
    	Row titleRow = sheet.createRow(0);
		titleRow.setHeightInPoints(45);		//行高
		Cell titleCell = titleRow.createCell(0);
		titleCell.setCellValue(tableTitle);
		titleCell.setCellStyle(styles.get("tableTitle"));
		sheet.addMergedRegion(CellRangeAddress.valueOf("$A$1:$L$1"));
    }
    
    /**
     * 创建头部
     * @param sheet
     * @param styles
     * @param headers
     */
    private static void createExecleHeader(Sheet sheet, Map<String, CellStyle> styles, List<String> headers){
    	Row headerRow = sheet.createRow(1);
		headerRow.setHeightInPoints(40);		//行高
		for (int i = 0; i < headers.size(); i++) {
			Cell headerCell = headerRow.createCell(i);
			headerCell.setCellValue(headers.get(i));
			headerCell.setCellStyle(styles.get("headers"));
		}
    }
    
    /**
     * 创建内容体
     * @param sheet
     * @param styles
     * @param execleView
     * @param workBook
     */
    private static void createExecleBody(Sheet sheet, Map<String, CellStyle> styles, ExecleDocument execleView, Workbook workBook){
    	int row = 2;
    	List<String> headers = execleView.getHeaders();
    	Collection<?> beans = execleView.getBeans();
		for (Object obj : beans) {
			Row bodyRow = sheet.createRow(row++);
			Field[] fields = obj.getClass().getDeclaredFields();
			for (int j = 0; j < headers.size() && j < fields.length; j++) {
				Cell bodyCell = bodyRow.createCell(j);
				Field field = fields[j ];
				Object returnType = ReflectionUtils.invokeGetterMethod(obj, field.getName());
				if(returnType == null){
					continue;
				}
				if(returnType.getClass() == byte[].class){		//图片
					if(execleView.getImgWidth() == null || execleView.getImgHeight() == null){			//图片默认60*80
						 //sheet.autoSizeColumn(j);
						// 有图片时，设置行高为60px;
						bodyRow.setHeightInPoints(60);
	                    // 设置图片所在列宽度为80px,注意这里单位的一个换算
						sheet.setColumnWidth(j, (short) (35.7 * 80));
					}else{
						// 有图片时，设置行高为60px;
						bodyRow.setHeightInPoints(execleView.getImgHeight());
	                    // 设置图片所在列宽度为80px,注意这里单位的一个换算
						sheet.setColumnWidth(j, (short) (35.7 * execleView.getImgWidth()));
					}
                    HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0,
                            1023, 255, (short) 6, row - 1, (short) 6, row - 1);
                    anchor.setAnchorType(2);
                    // 声明一个画图的管理器
                    Drawing patriarch = sheet.createDrawingPatriarch();
                    patriarch.createPicture(anchor, workBook.addPicture(
                    		(byte[])returnType, HSSFWorkbook.PICTURE_TYPE_JPEG));
					
				}else if(returnType.getClass() == Date.class){			//日期
					bodyCell.setCellValue(CalendarUtil.toString((Date)returnType, execleView.getPattern()));
				}else{											//其他一律文字处理
					bodyCell.setCellValue(returnType.toString());
				}
				bodyCell.setCellStyle(styles.get("body"));
			}
		}
    }
    
    
    
    /**
     * 创建样式
     * @param wb
     * @return
     */
    private static Map<String, CellStyle> createStyles(Workbook wb){
    	 Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
         CellStyle style;
       /*  Font titleFont = wb.createFont();
         titleFont.setFontHeightInPoints((short)20);
         titleFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
         style = wb.createCellStyle();
         style.setAlignment(CellStyle.ALIGN_CENTER);
         style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
         style.setFont(titleFont);
         styles.put("tableTitle", style);
         
         
         titleFont.setFontHeightInPoints((short)15);
         style.setFont(titleFont);
         styles.put("headers", style);
         
         
         titleFont.setFontHeightInPoints((short)12);
         titleFont.setBoldweight(Font.BOLDWEIGHT_NORMAL);
         style.setFont(titleFont);
         styles.put("body", style);*/
         
         
         Font titleFont = wb.createFont();
         titleFont.setFontHeightInPoints((short)18);
         titleFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
         style = wb.createCellStyle();
         style.setAlignment(CellStyle.ALIGN_CENTER);
         style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
         style.setFont(titleFont);
         styles.put("tableTitle", style);

         Font monthFont = wb.createFont();
         monthFont.setFontHeightInPoints((short)15);
         monthFont.setColor(IndexedColors.WHITE.getIndex());
         style = wb.createCellStyle();
         style.setAlignment(CellStyle.ALIGN_CENTER);
         style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
         style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
         style.setFillPattern(CellStyle.SOLID_FOREGROUND);
         style.setFont(monthFont);
         style.setWrapText(true);
         styles.put("headers", style);

         style = wb.createCellStyle();
         monthFont.setFontHeightInPoints((short)12);
         style.setAlignment(CellStyle.ALIGN_CENTER);
         style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
         styles.put("body", style);

         return styles;
    }
    
    
  
}